import { TabsPage } from './../../tabs/tabs';
import { HomePage } from './../../home/home';
import { Component, Injector,ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams,Slides } from 'ionic-angular';
import { BasePage } from '../../basePage';
import { StorageService } from './../../../providers/StorageService';
import { UserService } from './../../../providers/UserService';
import { PIC_URL } from "./../../../providers/Config";
import { nailerService } from './../../../providers/nailerService';

declare var Swiper;


/**
 * Generated class for the CollectionPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-collection',
  templateUrl: 'collection.html',
})
export class CollectionPage extends BasePage {

  picrooturl = "";//图片服务地址
  userinfo = {};
  collectionlist = [];  //收藏的美图
  serviceList=[];       //收藏的服务
  activation = false;  //激活图片删除
  flag1:false;          //没有网络时不显示该缺省页
  flag2:boolean;        //无美图提示控制器
  flag3:boolean;        //无服务提示控制器
  search:boolean;    //搜索栏控制器 
  allof:boolean=false;    //美图全选控制器
  allof1:boolean=false;    // 服务全选按钮控制器
  
  searchObj={
    user_id:0,
    collect_type:1
  }
  content:'';
  isPage=0;  //判断在哪个页面里
  allPics=0;   //美图总数
  allSers=0;   //服务总数
  
  swiper: any;
  @ViewChild('contentSlides') contentSlides: Slides;
  items: Array<any> = [0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8];
  menus: Array<string> = ["美图", "服务"]
  
  constructor(injector: Injector, public userService: UserService,public stc: StorageService,public nailerService:nailerService) {
    super(injector);
    this.picrooturl = PIC_URL
    this.userinfo = this.stc.read('userinfo');
   
  }

  ionViewDidLoad() {
    this.initSwiper();
    console.log('ionViewDidLoad CollectionPage');
    this.getUserCollectionAPI();
    this.getService();
    if(this.collectionlist.length==0){
      this.flag2=true;
    }else{
      this.flag2=false;
    }
    if(this.serviceList.length==0){
      this.flag3=true;
    }else{
      this.flag3=false;
    }
    console.log(this.isPage)
  }
  //*页面要进入的时候执行的函数  再页面加载之后执行  页面中一些函数已经执行完成  所以this.contentSliders 函数已经解析完成 */
  ionViewWillEnter(){
    // this.stuPage = this.navParams.data.stu;
    
  }
   dismissCLI() {
    this.viewCtrl.dismiss();
  }

/**初始化 */
  initSwiper() {
    this.swiper = new Swiper('.pageMenuSlides .swiper-container', {
      slidesPerView: 4,
      spaceBetween: 0,
      breakpoints: {
        1024: {
          slidesPerView: 4,
          spaceBetween: 0
        },
        768: {
          slidesPerView: 4,
          spaceBetween: 0
        },
        640: {
          slidesPerView: 4,
          spaceBetween: 0
        },
        320: {
          slidesPerView: 4,
          spaceBetween: 0
        }
      }
    });
  }
  /**点击选择 */
  selectPageMenu($event, index) {
    this.setStyle(index);
    this.contentSlides.slideTo(index);
  }
  /**样式切换选中 */
  setStyle(index) {
    var slides = document.getElementsByClassName('pageMenuSlides')[0].getElementsByClassName('swiper-slide');
    if (index < slides.length) {
      for (var i = 0; i < slides.length; i++) {
        var s = slides[i];
        s.className = "swiper-slide";
      }
      slides[index].className = "swiper-slide bottomLine";
    }
  }
   /**滑动选择 */
  slideChanged() {
    let index = this.contentSlides.getActiveIndex();
    this.setStyle(index);
    this.swiper.slideTo(index, 300);
    this.isPage=index;
    console.log(this.isPage)
  }
 

  /**启用删除小图标 */
  activationCLI() {
    this.activation = true;
  }

  /**完成启用图标 */
  activationokCLI() {
    this.activation = false;
  }

 

  /**美图全选 */
  selectall() {
    if (this.collectionlist.length > 0) {
      if(this.allof){
          for(let i=0;i<this.collectionlist.length;i++){
              this.collectionlist[i]['select'] = false;
              this.collectionlist[i]['selectimg'] = "assets/img/selectno1.png";
          }
          this.allof=false;  
      }else{
        for(let i=0;i<this.collectionlist.length;i++){
              this.collectionlist[i]['select'] = true;
              this.collectionlist[i]['selectimg'] = "assets/img/selectok.png";
        }
        this.allof=true;
      }
     
    }
  }
  /**
   * 服务全选
   */
  selectall1(){
    if (this.serviceList.length > 0) {
      if(this.allof1){
        for(let i=0;i<this.serviceList.length;i++){
            this.serviceList[i]['select'] = false;
            this.serviceList[i]['selectimg'] = "assets/img/selectno1.png";
          }
         this.allof1=false;
      }else{
        for(let i=0;i<this.serviceList.length;i++){
            this.serviceList[i]['select'] = true;
            this.serviceList[i]['selectimg'] = "assets/img/selectok.png";
        }
        this.allof1=true;
      }
      
    }
  }

  /**
   * 点击选中单个美图，再点取消选中
   * @param j 
   * @param index 
   */
  selectCLI(j) {
    let countall=[]     //计算所有没选中的
    let countall2=[]    //计算所有选中的
    if (this.collectionlist[j]["select"]) {
      this.collectionlist[j]["select"] = false;
      this.collectionlist[j]["selectimg"] = "assets/img/selectno1.png";
      for(let i=0;i<this.collectionlist.length;i++){
          if(this.collectionlist[i]["select"]==false){
            countall.push(this.collectionlist[i]['nail_id']);
          }
      }
      if(countall.length>0){
        this.allof=false;
      }
    } else {
      this.collectionlist[j]["select"] = true;
      this.collectionlist[j]["selectimg"] = "assets/img/selectok.png";
      for(let i=0;i<this.collectionlist.length;i++){
          if(this.collectionlist[i]["select"]){
            countall2.push(this.collectionlist[i]['nail_id']);
          }
      }
      if(countall2.length==this.allPics){
        this.allof=true;
      }
    }
  }

  /**
   * 点击选中服务，再点取消选中服务
   * @param m 外层时间的索引
   * @param index 内层数据列表的索引
   */
  selectCLI1(m){
    let countall=[]     //计算所有没选中的
    let countall2=[]    //计算所有选中的
    //如果该按钮选中
    if (this.serviceList[m]["select"]) {
      this.serviceList[m]["select"] = false;
      this.serviceList[m]["selectimg"] = "assets/img/selectno1.png";
      for(let i=0;i<this.serviceList.length;i++){
          if(this.serviceList[i]["select"]==false){
            countall.push(this.serviceList[i]['nail_id']);
          }
      }
      if(countall.length>0){
        this.allof1=false;
      }
    } else {
      this.serviceList[m]["select"] = true;
      this.serviceList[m]["selectimg"] = "assets/img/selectok.png";
      for(let i=0;i<this.serviceList.length;i++){
          if(this.serviceList[i]["select"]){
            countall2.push(this.serviceList[i]['nail_id']);
          }
      }
      if(countall2.length==this.allSers){
        this.allof1=true;
      }else{
        this.allof1=false;
      }
    }
  }

   /**
    * 删除美图
   */
  async cancelCollectNailAPI() {
    let id = [];
    for(let i=0;i<this.collectionlist.length;i++){
        if(this.collectionlist[i]["select"]){
          id.push(this.collectionlist[i]['nail_id']);
        }
    }
    if(id.length==0){
      let toast = this.toastCtrl.create({
              message: '请选择要删除的选项',
              duration: 1500,
              position: 'bottom',
            })
      toast.present();
    }else{
      let collected_ids=id.toString();
      //collected_type:1 删除美图
      let param = { 'user_id': this.userinfo['user_id'], 'collected_ids': collected_ids,'collected_type':1 };
      let result = await this.userService.cancelCollectNailAPI(param);
      console.log(result)
      if(result.code != 1){
      let toast = this.toastCtrl.create({
            message: result.msg,
            duration: 1500,
            position: 'bottom',
          })
        toast.present();
      }else{
        let toast = this.toastCtrl.create({
            message: result.msg,
            duration: 1500,
            position: 'bottom',
          })
        toast.present();
        setTimeout(()=> {
          this.getUserCollectionAPI();
        }, 300);
      }
    }
  }

  /**
   * 删除服务
   */
  async cancelCollectNailAPI1(){
    let id = [];
    for(let i=0;i<this.serviceList.length;i++){
        if(this.serviceList[i]["select"]){
          id.push(this.serviceList[i]['service_id']);
        }
    }
    if(id.length==0){
      let toast = this.toastCtrl.create({
              message: '请选择要删除的选项',
              duration: 1500,
              position: 'bottom',
            })
      toast.present();
    }else{
      let collected_ids=id.toString();
      //collected_type:2 删除服务
      let param = { 'user_id': this.userinfo['user_id'], 'collected_ids': collected_ids,'collected_type':2 };
      let result = await this.userService.cancelCollectNailAPI(param);
      console.log(result)
      if(result.code != 1){
      let toast = this.toastCtrl.create({
            message: result.msg,
            duration: 1500,
            position: 'bottom',
          })
        toast.present();
      }else{
        let toast = this.toastCtrl.create({
            message: result.msg,
            duration: 1500,
            position: 'bottom',
          })
        toast.present();
        setTimeout(()=> {
          this.getService();
        }, 300);
      }
    }
  }
 

  /**收藏的美图 */
  async getUserCollectionAPI() {
    let param = { 'user_id': this.userinfo['user_id'], 'collect_type':1 };
    let loader = this.loadingCtrl.create({
      content: "",
    });
    loader.present();
    let result = await this.userService.getUserCollectionAPI(param);
    loader.dismiss();
    console.log(result)
    //fail
    if (result.code == 1) {
     //获取成功并有数据
      if(result.data.length==0){
        this.flag2=true;
      }else{
        this.collectionlist = result.data;
        this.picCounts();
        this.flag2=false;
        this.collectionlist.forEach((e,i)=>{
          e['select'] = false;
          e['selectimg'] = "assets/img/selectno1.png";
        })
      }
    }else{
      let toast = this.toastCtrl.create({
        message: result.msg,
        duration: 2000,
        position: 'bottom',
      })
      toast.present();
      this.flag2=true;
    }
  }
  //收藏的服务
  async getService() {
    let param = { 'user_id': this.userinfo['user_id'], 'collect_type':2 };
    let loader = this.loadingCtrl.create({
      content: "",
    });
    loader.present();
    let result = await this.userService.getUserCollectionAPI(param);
    loader.dismiss();
    console.log(result)
    if (result.code == 1) {
      //获取成功并有数据
      this.serviceList = result.data;
      console.log(this.serviceList);
      if (this.serviceList.length > 0) {
        this.flag3=false;
        //this.flag2=false;
        this.serCounts();
        this.serviceList.forEach((e,i) => {
                e['select'] = false;
                e['selectimg'] = "assets/img/selectno1.png";
        });
        // for (let i = 0; i < this.serviceList.length; i++) {
        //   this.serviceList[i]['select'] = false;
        //   this.serviceList[i]['selectimg'] = "assets/img/selectno1.png";
        // }
      }
      console.log(this.serviceList);
    } else {
      let toast = this.toastCtrl.create({
        message: result.reason,
        duration: 2000,
       position: 'bottom',
      })
      toast.present();
      this.flag3=true;
    }
  }
  /**
   * 计算所有的美图总数
   */
  picCounts(){
    let eachCount=0;
    eachCount+=this.collectionlist.length;
    console.log(eachCount);
    // for(let i=0;i<this.collectionlist.length;i++){
    //   eachCount+=this.collectionlist[i].nail.length;
    //   console.log(eachCount);
    // }
    this.allPics=eachCount
    console.log("总共有"+this.allPics);
  }
  /**
   * 计算所有的服务总数
   */
  serCounts(){
    let eachCount=0;
    eachCount+=this.serviceList.length;
    console.log(eachCount);
    // for(let i=0;i<this.serviceList.length;i++){
    //   eachCount+=this.serviceList[i].data.length;
    //   console.log(eachCount);
    // }
    this.allSers=eachCount
    console.log("总共有"+this.allSers);
  }

  // /*点击更新*/
  // reload(){
  //  location.reload();
  // }
  /*去首页*/
  home(){
    this.navCtrl.setRoot(TabsPage);
  }
  /** 跳转美甲款式详情 */
  showGoodsDetail(i) {
    let modal = this.modalCtrl.create('ImgInfoPage', { "id": i });
    modal.present();
   // this.navCtrl.push("ImgInfoPage")
   //console.log(this.styleMore[i].nail_id)
   //this.appCtrl.getRootNavById('N4').push('ImgInfoPage',)

 }
  /** 跳转服务详情 */
  showGoodsDetail2(i) {
    let modal = this.modalCtrl.create('ShopInfoPage', { "id": i });
    modal.present();
   // this.navCtrl.push("ImgInfoPage")
   //console.log(this.styleMore[i].nail_id)
   //this.appCtrl.getRootNavById('N4').push('ImgInfoPage',)

 }
  /**
   *控制搜索栏的显示和隐藏 
   */
  searchby(){
      this.search =true;
  }
  /**
   * 失去焦点时判断是否收起搜索栏
   */
  change(){
    if(this.content==undefined||this.content.length==0){
      this.search=false;
      this.getUserCollectionAPI();
      this.getService();
    }
    console.log(this.content);
  }
  /**
   * 内容改变时搜索
   */
  async searchC(){
    // if(this.content==""){
    //   this.getUserCollectionAPI();
    //   this.getService();
    // }else{
        if(this.isPage==0){
          this.collectionlist=[];
          console.log("开始搜索美图")
          let param={user_id:this.userinfo['user_id'],search_key:this.content,type:1}
          let res = await this.nailerService.searchCollectionAPI(param);
          if(res.code==1){
            this.rewritePic(res);
          }
        }else if(this.isPage==1){
          this.serviceList=[];
          console.log("开始搜索服务")
          let param={user_id:this.userinfo['user_id'],search_key:this.content,type:3}
          let res = await this.nailerService.searchCollectionAPI(param);
          console.log(res)
          if(res.code==1){
              this.rewriteSer(res);
          }
          console.log(this.serviceList)
        }
    // }
    
  }
  /**
   *根据搜索结果重构美图页面
   * @param res 搜索结果美图
   */
  rewritePic(res){
      
      //搜索美图
      console.log("开始搜索美图")
      //因为获取到的数据与搜索出来的数据结构不同，所以
      //也是强行创造一个二维数组，字段名也不一样，所以字段名也重新添加了
      this.collectionlist=res.data;
      this.collectionlist.forEach((e,i) => {
          e['nail_id']=e.id;
          e['nail_middle_url']=e.nail_small_url;
      });
      // this.collectionlist[0]['nail']=res.data;
      // this.collectionlist[0].nail.forEach((e,i) => {
      //   e['nail_id']=e.id;
      //   e['nail_middle_url']=e.nail_small_url;
      // });
  }

  /**
   * 根据搜索结果重构服务页面
   * @param res 搜索结果服务
   */
  rewriteSer(res){
   
    if(res.data != null){
      this.serviceList=res.data;
      this.serviceList.forEach((e,i) => {
        e['service_image']=e.service_img;
      });
    }else{
      let toast = this.toastCtrl.create({
        message: '匹配到的数据信息为空',
        duration: 1500,
        position: 'bottom',
      })
      toast.present();
    }
    
        // this.serviceList[0]['data']=res.data;
        // this.serviceList[0].data.forEach((e,i) => {
        //   e['service_image']=e.service_img;
        // });
        // console.log(this.serviceList)
    
  }
  /**
   * 点击搜索进一步提示
   */
  async confirm(){
     if(this.content==""){
       this.getUserCollectionAPI();
       this.getService();
     }else{
       if(this.isPage==0){
         console.log("开始搜索美图");
         let param={user_id:this.userinfo['user_id'],search_key:this.content,type:1}
         let res = await this.nailerService.searchCollectionAPI(param);
         console.log(res)
         if(res.data.length!=0){
            this.rewritePic(res);
         }else{
            let toast = this.toastCtrl.create({
              message: res.msg,
              duration: 2000,
              position: 'bottom',
            })
            toast.present();
         }
       }else if(this.isPage==1){
         console.log("开始搜索服务");
          let param={user_id:this.userinfo['user_id'],search_key:this.content,type:3}
          let res = await this.nailerService.searchCollectionAPI(param);
          console.log(res);
          if(res.code == 1){
              this.rewriteSer(res);
          }else if(res.code==0){
            let toast = this.toastCtrl.create({
              message: res.msg,
              duration: 1500,
              position: 'bottom',
            })
            toast.present();
          }
       }
     }
 
  }
}
